package cn.ssm.controller;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHandlerInterceptor implements HandlerInterceptor {
    // 调用目标方法前请求
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 尝试从会话中获取登录用户信息
        Object loginUser = request.getSession().getAttribute("loginUser");
        if (loginUser != null) {
            // 用户已登录，放行请求
            return true;
        }
        // 用户未登录, 转发到登录页面
        request.setAttribute("msg", "无权限，请登录后访问！");
        request.getRequestDispatcher("/index.html").forward(request, response);
        return false;
    }
}
